﻿using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.Domain.Products;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;
using MySqlX.XDevAPI.Common;
using Org.BouncyCastle.Asn1.Ocsp;
using ZstdSharp.Unsafe;

namespace MangoMes.Write.API.Applications.ProductTyped
{
    /// <summary>
    /// 物料产品分类 列表
    /// </summary>
    public class ProductTypesSearchHandler : IRequestHandler<ProductTypesSearchCommand, ResultsDTO<ProductTypeDto>>
    {
        #region 仓储
        /// <summary>
        /// 仓储
        /// </summary>
        private readonly IBateRepository<ProductTypes> ProductTypesRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="productTypesRepository">物料产品分类</param>
        public ProductTypesSearchHandler(IBateRepository<ProductTypes> productTypesRepository)
        {
            ProductTypesRepository = productTypesRepository;
        }
        #endregion

        #region 物料产品分类 显示列表
        /// <summary>
        /// 物料产品分类 显示列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultsDTO<ProductTypeDto>> Handle(ProductTypesSearchCommand request, CancellationToken cancellationToken)
        {
            //异常处理
            try
            {
                //创建DapperHelper对象 用于与数据库进行交互
                DapperHelper dapperHelper = new DapperHelper();
                //初始化一个ResultDTO<ProductTypeDto>对象result，并设置Code为 0
                ResultsDTO<ProductTypeDto> result = new ResultsDTO<ProductTypeDto>() { Code = 0 };
                //连接mySql连接到指定的数据库
                string conn = "server=112.124.69.237;port=3306;uid=root;pwd=No6123666;database=MangoMesDB";
                //创建对象 pro
                ProductTypes pro = new ProductTypes();

                //sql语句
                string str = $"select * from producttypes where 1=1";

                //查询条件：分类名称（模糊查询） 启用状态
                if (!string.IsNullOrEmpty(request.ProductTypeName))
                {
                    str += $" and ProductTypeName like '%{request.ProductTypeName}%'";
                }
                if (request.ProductState > 0)
                {
                    str += $" and ProductState={request.ProductState}";
                }
                //使用了字符串拼接操作 str是一个已有的字符串
                //通过+=操作将" and Pid = 0"添加到str的末尾，得到一个新的字符串并赋值给res
                var res = str += $" and Pid = 0";
                var list = ProductTypesRepository.GetAll(res, pro, conn);
                //执行查询并获取结果res 然后通过遍历结果集
                //将每个产品类型的信息填充到ProductTypeDto对象中，并添加到dto列表中。
                List<ProductTypeDto> dto = new List<ProductTypeDto>();
                foreach (var item in list)
                {
                    ProductTypeDto pros = new ProductTypeDto();
                    pros.ProductTypeId = item.ProductTypeId;
                    pros.ProductTypeName = item.ProductTypeName;
                    pros.ProductDescs = item.ProductDescs;
                    pros.ProductZoo = item.ProductZoo;
                    pros.ProductState = item.ProductState;
                    pros.Pid = item.Pid;
                    pros.Children = fangFa(item.ProductTypeId, request.ProductTypeName);
                    dto.Add(pros);

                }

                result.Data = dto;
                result.Message = "查询成功";

                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 树形
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="productTypeName"></param>
        /// <returns></returns>
        public List<ProductTypeDto> fangFa(int pid, string productTypeName)
        {
            //创建实例化
            ProductTypes productTypes = new ProductTypes();
            //定义了一个数据库连接字符串conn
            //服务器地址（112.124.69.237）
            //端口号（3306）用户名（root）密码（No6123666）和数据库名称（MangoMesDB）用于连接到指定的数据库
            string conn = "server=112.124.69.237;port=3306;uid=root;pwd=No6123666;database=MangoMesDB";
            string str = $"select * from producttypes where pid={pid}";
            var list1 = ProductTypesRepository.GetAll(str, productTypes, conn).ToList();
            if (!string.IsNullOrEmpty(productTypeName))
            {
                list1 = list1.Where(x => x.ProductTypeName.Contains(productTypeName)).ToList();
            }
            //创建新的dto 存储最终要返回的产品类型数据
            List<ProductTypeDto> dto = new List<ProductTypeDto>();
            foreach (var item in list1) //遍历前面经过筛选得到的list1列表每个元素item
            {
                var lists = new ProductTypes(); //父节点名称
                if (item.Pid > 0)
                {
                    //获取父节点名称
                    //如果item.Pid不为 0（即不是根节点），则根据pid获取子节点信息并添加到lists中
                    lists = ProductTypesRepository.GetAll("select * from producttypes", productTypes, conn).Where(x => x.ProductTypeId == item.Pid).FirstOrDefault();
                }
                else
                {
                    lists.ProductTypeName = ""; //如果item.Pid为 0 则lists.ProductTypeName为空的字符串
                }
                ProductTypeDto pros = new ProductTypeDto();
                pros.ProductTypeId = item.ProductTypeId;
                pros.ProductTypeName = item.ProductTypeName;
                pros.ProductDescs = item.ProductDescs;
                pros.ProductZoo = item.ProductZoo;
                pros.ProductState = item.ProductState;
                pros.Pid = item.Pid;
                //构建新的sql查询字符串 用于查询当前节点的子节点，条件是pid等于当前节点的ProductTypeId
                string stra = $"select * from producttypes where pid={item.ProductTypeId}";
                //执行上述查询，获取子节点列表list2
                var list2 = ProductTypesRepository.GetAll(stra, productTypes, conn).ToList();
                foreach (var items in list2)
                {
                    List<ProductTypeDto> dtos = new List<ProductTypeDto>();
                    ProductTypeDto pros2 = new ProductTypeDto();
                    pros2.ProductTypeId = items.ProductTypeId;
                    pros2.ProductTypeName = items.ProductTypeName;
                    pros2.ProductDescs = items.ProductDescs;
                    pros2.ProductZoo = items.ProductZoo;
                    pros2.ProductState = items.ProductState;
                    pros2.Pid = items.Pid;
                    pros.Children = fangFa(item.ProductTypeId, productTypeName);
                }
                dto.Add(pros);

            }
            return dto; //返回Dto
        }
        #endregion
    }

}
